package com.nuaa.ange.controller;

import com.nuaa.ange.annotation.ApiLog;
import com.nuaa.ange.common.lang.RespBean;
import com.nuaa.ange.utils.RandomUtil;
import com.nuaa.ange.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @description
 * @author 玦离
 * @date 2022/12/31 19:35
 */

@RestController
@Api(tags = "腾讯云短信服务相关接口")
@RequestMapping("/sms")
public class SmsController extends BaseController{

    @ApiOperation(value = "发送短信")
    @GetMapping(value = "/send/{phone}")
    @ApiLog
    public RespBean sendCode(@RequestParam("phone") String phone) {
        String code = RedisUtil.get(phone);
        if (!StringUtils.isEmpty(code)) {
            return RespBean.ok("已发送验证码，请勿多次点击发送");
        }

        String vcode = RandomUtil.getSixBitRandom();
        boolean isSend = smsService.send(phone, vcode);
        if(isSend) {
            // 验证码1分钟失效
            boolean isSet = RedisUtil.set(phone, vcode, 1);
            if (isSet) {
                return RespBean.ok("success", "发送短信成功");
            }
        }
        return RespBean.error("发送短信失败");
    }

    @ApiOperation(value = "验证验证码")
    @GetMapping("/check")
    @ApiLog
    public RespBean checkCode (@RequestParam("phone") String phone, @RequestParam("code") String code) {
        String vcode = RedisUtil.get(phone);
        if (Objects.equals(vcode, code) && (vcode != null)) {
            return RespBean.ok("验证码验证成功");
        }
        return RespBean.error("验证码验证失败");
    }
}
